package com.example.myapplication

import android.Manifest
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ProgressBar
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.myapplication.function.musicmode.EnhancedMelodyAnalyzer
import com.example.myapplication.function.musicmode.NoiseAwareHummingRecognitionEngine
import com.example.myapplication.function.musicmode.PianoRollView
import com.example.myapplication.function.musicmode.WaveFormView


class MusicModeRecognizerActivity : AppCompatActivity() {


    //    private lateinit var recognitionEngine: HummingRecognitionEngine
    private lateinit var recognitionEngine: NoiseAwareHummingRecognitionEngine

    // UI组件
    private lateinit var btnRecord: Button
    private lateinit var tvCurrentNote: TextView
    private lateinit var tvKeyResult: TextView
    private lateinit var tvConfidence: TextView
    private lateinit var progressBar: ProgressBar
    private lateinit var waveFormView: WaveFormView
    private lateinit var pianoRollView: PianoRollView
    private lateinit var tvNoiseLevel: TextView
    private lateinit var noiseLevelProgress: ProgressBar
    private lateinit var modeSelector: Spinner

    private var isRecording = false
    private val handler = Handler(Looper.getMainLooper())
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_music_mode_recognizer)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initViews()
        setupRecognitionEngine()
        setupModeSelector()
        checkPermissions()

    }


    // 在Activity中添加这些权限处理方法
    private fun checkPermissions() {
        val requiredPermissions = arrayOf(
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE // 如果需要保存录音
        )

        val missingPermissions = requiredPermissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }

        if (missingPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                missingPermissions.toTypedArray(),
                REQUEST_AUDIO_PERMISSION
            )
        }
    }

    private fun initViews() {
        btnRecord = findViewById(R.id.btn_record)
        tvCurrentNote = findViewById(R.id.tv_current_note)
        tvKeyResult = findViewById(R.id.tv_key_result)
        tvConfidence = findViewById(R.id.tv_confidence)
        progressBar = findViewById(R.id.progress_bar)
        waveFormView = findViewById(R.id.wave_form_view)
        pianoRollView = findViewById(R.id.piano_roll_view)

        // 新增的噪音相关UI
        tvNoiseLevel = findViewById(R.id.tv_noise_level)
        noiseLevelProgress = findViewById(R.id.noise_level_progress)
        modeSelector = findViewById(R.id.mode_selector)

        btnRecord.setOnClickListener {
            if (isRecording) {
                stopRecognition()
            } else {
                startRecognition()
            }
        }
        // 初始化UI状态
        updateUIState(false)

        // 学习环境噪音按钮
        findViewById<Button>(R.id.btn_learn_noise).setOnClickListener {
            learnEnvironmentNoise()
        }
    }

    private fun setupRecognitionEngine() {
//        recognitionEngine = HummingRecognitionEngine()
        recognitionEngine = NoiseAwareHummingRecognitionEngine()
        recognitionEngine.initialize()

        // 设置实时分析回调
        recognitionEngine.onRealTimeAnalysis = { analysis ->
            runOnUiThread {
                updateRealTimeDisplay(analysis)
            }
        }

        // 设置最终结果回调
        recognitionEngine.onFinalResult = { result ->
            runOnUiThread {
                displayFinalResult(result)
            }
        }

        // 设置音频处理回调（用于波形显示）
        recognitionEngine.onAudioProcessed = { audioData ->
            runOnUiThread {
                updateWaveForm(audioData)
            }
        }
    }

    private fun setupModeSelector() {
        val modes = NoiseAwareHummingRecognitionEngine.NoiseReductionMode.values()
        val modeNames = modes.map {
            when(it) {
                NoiseAwareHummingRecognitionEngine.NoiseReductionMode.NONE -> "无降噪"
                NoiseAwareHummingRecognitionEngine.NoiseReductionMode.BASIC -> "基本降噪"
                NoiseAwareHummingRecognitionEngine.NoiseReductionMode.ADVANCED -> "高级降噪"
                NoiseAwareHummingRecognitionEngine.NoiseReductionMode.SPECTRAL -> "频域降噪"
            }
        }

        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, modeNames)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        modeSelector.adapter = adapter

        // 设置默认选择高级降噪
        modeSelector.setSelection(2)

        modeSelector.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
                val selectedMode = modes[position]
                recognitionEngine.setNoiseReductionMode(selectedMode)
                showToast("降噪模式: ${modeNames[position]}")
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }
    }

    private fun updateNoiseLevelDisplay(noiseLevel: Float) {
        val noisePercent = (noiseLevel * 100).toInt()
        tvNoiseLevel.text = "环境噪音: $noisePercent%"
        noiseLevelProgress.progress = noisePercent

        // 根据噪音水平改变颜色
        val color = when {
            noiseLevel < 0.3 -> ContextCompat.getColor(this, R.color.confidence_high)
            noiseLevel < 0.7 -> ContextCompat.getColor(this, R.color.confidence_medium)
            else -> ContextCompat.getColor(this, R.color.confidence_low)
        }
        noiseLevelProgress.progressTintList = ColorStateList.valueOf(color)
    }

    private fun updateWaveForm(audioData: FloatArray) {
        // 计算音频数据的平均幅度用于波形显示
        var sum = 0f
        for (sample in audioData) {
            sum += Math.abs(sample)
        }
        val averageAmplitude = sum / audioData.size
        waveFormView.updateAmplitude(averageAmplitude)
    }

    private fun updateRealTimeDisplay(analysis: EnhancedMelodyAnalyzer.RealTimeAnalysis) {
        tvCurrentNote.text = "当前音符: ${analysis.currentNote}"

        // 更新波形显示
        waveFormView.updateAmplitude(analysis.confidence.toFloat())

        // 更新钢琴卷帘
        pianoRollView.addNote(analysis.currentNote, analysis.confidence)

        // 更新置信度指示器
        updateConfidenceIndicator(analysis.confidence)
    }

    private fun displayFinalResult(result: EnhancedMelodyAnalyzer.MelodyAnalysisResult) {
        val stringBuilder = StringBuilder()

        // 显示最可能的调式
        result.mostLikelyKey?.let { key ->
            stringBuilder.append("🎵 最可能调式: ${key.scale.getScaleName()}\n")
            stringBuilder.append("✅ 置信度: ${(key.confidence * 100).toInt()}%\n\n")
        }

        // 显示所有可能的调式（前3个）
        if (result.keyResults.size > 1) {
            stringBuilder.append("其他可能调式:\n")
            result.keyResults.take(3).forEachIndexed { index, keyResult ->
                if (index > 0) {
                    stringBuilder.append("• ${keyResult.scale.getScaleName()} (${(keyResult.confidence * 100).toInt()}%)\n")
                }
            }
            stringBuilder.append("\n")
        }

        // 显示音符分布
        stringBuilder.append("🎹 检测到的音符:\n")
        result.noteDistribution.entries.sortedByDescending { it.value }
            .take(8) // 只显示前8个最频繁的音符
            .forEach { (note, count) ->
                stringBuilder.append("• $note: $count 次\n")
            }

        stringBuilder.append("\n🎼 节奏: ${result.tempo.toInt()} BPM")
        stringBuilder.append("\n📊 整体置信度: ${(result.confidence * 100).toInt()}%")

        tvKeyResult.text = stringBuilder.toString()
        tvKeyResult.setTextColor(ContextCompat.getColor(this, R.color.primary_text))
    }

    private fun updateConfidenceIndicator(confidence: Double) {
        val confidencePercent = (confidence * 100).toInt()
        tvConfidence.text = "$confidencePercent%"

        when {
            confidence > 0.8 -> {
                tvConfidence.setBackgroundColor(ContextCompat.getColor(this, R.color.confidence_high))
                tvConfidence.setTextColor(Color.WHITE)
            }
            confidence > 0.6 -> {
                tvConfidence.setBackgroundColor(ContextCompat.getColor(this, R.color.confidence_medium))
                tvConfidence.setTextColor(Color.WHITE)
            }
            else -> {
                tvConfidence.setBackgroundColor(ContextCompat.getColor(this, R.color.confidence_low))
                tvConfidence.setTextColor(Color.WHITE)
            }
        }
    }

    private fun updateUIState(recording: Boolean) {
        if (recording) {
            btnRecord.text = "停止识别"
            btnRecord.setBackgroundColor(ContextCompat.getColor(this, R.color.error))
            progressBar.visibility = View.VISIBLE
            tvCurrentNote.text = "正在检测..."
            tvKeyResult.text = "正在分析音阶和调式..."
            tvKeyResult.setTextColor(ContextCompat.getColor(this, R.color.secondary_text))
        } else {
            btnRecord.text = "开始哼唱"
            btnRecord.setBackgroundColor(ContextCompat.getColor(this, R.color.primary))
            progressBar.visibility = View.GONE
            tvCurrentNote.text = "-"
            tvConfidence.text = "0%"
            tvConfidence.setBackgroundColor(ContextCompat.getColor(this, R.color.confidence_low))
            waveFormView.clear()
            pianoRollView.clear()
        }
    }

    private fun startRecognition() {
        if (hasAudioPermission()) {
            recognitionEngine.startRecognition()
            isRecording = true
            updateUIState(true)
            showToast("开始哼唱识别 - 降噪模式: ${getCurrentModeName()}")
        } else {
            requestAudioPermission()
        }
    }

    private fun stopRecognition() {
        recognitionEngine.stopRecognition()
        isRecording = false
        updateUIState(false)
        showToast("识别结束")
    }

    private fun learnEnvironmentNoise() {
        showToast("正在学习环境噪音，请保持安静...")
        recognitionEngine.learnEnvironmentNoise(3000) // 学习3秒环境噪音
    }

    private fun getCurrentModeName(): String {
        return when(recognitionEngine.getCurrentMode()) {
            NoiseAwareHummingRecognitionEngine.NoiseReductionMode.NONE -> "无降噪"
            NoiseAwareHummingRecognitionEngine.NoiseReductionMode.BASIC -> "基本降噪"
            NoiseAwareHummingRecognitionEngine.NoiseReductionMode.ADVANCED -> "高级降噪"
            NoiseAwareHummingRecognitionEngine.NoiseReductionMode.SPECTRAL -> "频域降噪"
        }
    }

    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    // 权限检查方法（同前）
    private fun hasAudioPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestAudioPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.RECORD_AUDIO),
            REQUEST_AUDIO_PERMISSION
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_AUDIO_PERMISSION &&
            grantResults.isNotEmpty() &&
            grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startRecognition()
        } else {
            Toast.makeText(this, "需要录音权限才能使用哼唱识别功能", Toast.LENGTH_LONG).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        recognitionEngine.stopRecognition()
        handler.removeCallbacksAndMessages(null)
    }

    companion object {
        private const val REQUEST_AUDIO_PERMISSION = 123
    }
}